// 请求配置
import axios from 'axios'
import {
	Notification,
	Message
} from 'element-ui'
import {
	getToken
} from '@/utils/auth'

// 配置默认请求头: Content-Type
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
const requests = axios.create({
	baseURL: '/api',
	timeout: 10000
})

// 请求拦截器
requests.interceptors.request.use((config) => {

	// 将令牌丢入请求头传给后台
	const isToken = (config.headers || {}).isToken === false
	if (getToken() && !isToken) config.headers['tokenAuthorization'] = 'Bearer' + getToken()

	// 对请求方法进行JSON的封装

	if (config.method === 'post' || config.method === 'put') {
		const requestObj = {
			url: config.url,
			data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
			time: new Date().getTime()
		}
	}

	return config
}, error => {
	Promise.reject(error)
})


// 响应拦截器
requests.interceptors.response.use((res) => {
	const code = res.data.code || 200
	const msg = res.data.msg

	if (res.request.responseType === 'blob' || res.request.responseType == 'arraybuffer') return res.data;

	if (code === 401) {

		return Promise.reject('无效的会话，请重新登录。');

	} else if (code === 500) {

		Message({
			message: msg,
			type: 'error'
		})
		return Promise.reject()

	} else if (code != 200) {

		Notification.error({
			title: msg
		})

	} else return res.data;


}, (error) => {
	// 响应失败的回调函数
	console.log("响应失败" + error);
	let {
		message
	} = error;
	if (message == "Network Error") {
		message = "后端接口连接异常";
	} else if (message.includes("timeout")) {
		message = "系统接口请求超时";
	} else if (message.includes("Request failed with status code")) {
		message = "系统接口" + message.substr(message.length - 3) + "异常";
	}
	Message({
		message: message,
		type: 'error',
		duration: 5 * 1000
	})
	return Promise.reject(error)
})

export default requests;
